package cn.easybuy.service.product;

import cn.easybuy.utils.ShoppingCart;
import cn.easybuy.utils.ShoppingCartItem;

public class CartServiceImpl implements CartService {
	public ShoppingCart modifyShoppingCart(int productId, String quantityStr, ShoppingCart cart) throws Exception {
    	Integer quantity = 0;
    	if (quantityStr!=null)
            quantity = Integer.parseInt(quantityStr);
        //便利购物车寻找该商品 修改其数量
        for (ShoppingCartItem item : cart.getItems()) {
            if (item.getProduct().getId()==productId) {
            	//如果数量等于0或者小于0 则代表删除商品
                if (quantity == 0 || quantity < 0) {
                    cart.getItems().remove(item);
                    break;
                } else {
                    item.setQuantity(quantity);
                }
            }
        }
        //重新计算金额
        calculate(cart);
        return cart;
   }
   
    public ShoppingCart calculate(ShoppingCart cart) {
        cart.setSum(cart.getTotal());
        return cart;
    }

}
